package cpu.footprint.api;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import org.xutils.common.Callback.CommonCallback;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.ui.LoginActivity;

/**
 * Created by wjp on 2017/7/6.
 */

public class RespCallBack<ResultType> implements CommonCallback<ResultType> {
    private Context mContext;
    private String TAG="RespCallBack";
    public RespCallBack(Context context) {
        this.mContext = context;
    }

    @Override
    public void onSuccess(ResultType result) {
        BaseBean m = (BaseBean) result;
        if (!m.success) {
            if(mContext==null){
                return;
            }
            if (m.getCode() == 302) {
                Toast.makeText(mContext, "身份验证失败，请重新登录！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, LoginActivity.class);
                intent.putExtra("isError", true);
                mContext.startActivity(intent);
            }
            return;
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if(mContext==null){
            return;
        }
        if(ex==null){
            return;
        }
        Log.e(TAG,"error:"+ex.toString());
        if (ex.toString().contains("ConnectException") || ex.toString().contains("Internal Server Error")) {
            Toast.makeText(mContext, "服务器连接错误!", Toast.LENGTH_SHORT).show();
        } else if (ex.toString().contains("JsonSyntaxException")) {
            Toast.makeText(mContext, "数据请求错误!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCancelled(CancelledException cex) {
    }

    @Override
    public void onFinished() {
    }
}
